package server

import (
	"sync"
	"ws-demo-go/internal/message/common"
	"ws-demo-go/internal/transport/server"
	"ws-demo-go/pkg/logger"
)

type Connection struct {
	transConn *server.Connection // 底层传输层连接
	mu        sync.Mutex         // 保护 transConn 状态
}

// NewConnection 创建消息层连接实例
func NewConnection(transConn *server.Connection) *Connection {
	return &Connection{
		transConn: transConn,
	}
}

// SendMessage 发送 Message 消息
// TODO 以后可以考虑整一个对象池复用 msg
func (mc *Connection) SendMessage(msg *common.Message) error {
	mc.mu.Lock()
	defer mc.mu.Unlock()

	if mc.IsClosed() {
		return common.ErrConnectionClosed
	}

	// 编码Message为二进制数据
	data, err := common.Encode(msg)
	if err != nil {
		logger.Error("Encode message failed: %v", err)
		return err
	}

	// 通过传输层发送二进制数据
	return mc.transConn.SendBytes(data)
}

// ConnID 获取连接ID
func (mc *Connection) ConnID() string {
	return mc.transConn.GetConnID()
}

// Close 关闭连接
func (mc *Connection) Close() {
	mc.mu.Lock()
	defer mc.mu.Unlock()

	if mc.IsClosed() {
		return
	}

	mc.transConn.Close()
}

// IsClosed 检查连接是否关闭
func (mc *Connection) IsClosed() bool {
	return mc.transConn.IsClosed()
}
